home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-rdflib / rdflib / syntax / parsers / TriXHandler.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  7.6 KB  |  237 lines

  1. # Copyright (c) 2002, Daniel Krech, http://eikeon.com/
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. #   * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. #   * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. #   * Neither the name of Daniel Krech nor the names of its
  17. # contributors may be used to endorse or promote products derived
  18. # from this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  
  32. """
  33. """
  34. from rdflib import RDF, RDFS, Namespace
  35. from rdflib import URIRef, BNode, Literal
  36. from rdflib.Graph import Graph
  37. from rdflib.exceptions import ParserError, Error
  38. from rdflib.syntax.xml_names import is_ncname
  39.  
  40. from xml.sax.saxutils import handler, quoteattr, escape
  41. from urlparse import urljoin, urldefrag
  42.  
  43. RDFNS = RDF.RDFNS
  44.  
  45. TRIXNS=Namespace("http://www.w3.org/2004/03/trix/trix-1/")
  46.  
  47.  
  48. class TriXHandler(handler.ContentHandler):
  49.     """An Sax Handler for TriX. See http://swdev.nokia.com/trix/TriX.html"""
  50.  
  51.     def __init__(self, store):
  52.         self.store = store
  53.         self.preserve_bnode_ids = False
  54.         self.reset()
  55.  
  56.     def reset(self):
  57.         self.bnode = {}
  58.         self.graph=self.store
  59.         self.triple=None
  60.         self.state=0
  61.         self.lang=None
  62.         self.datatype=None
  63.  
  64.     # ContentHandler methods
  65.  
  66.     def setDocumentLocator(self, locator):
  67.         self.locator = locator
  68.  
  69.     def startDocument(self):
  70.         pass
  71.  
  72.     def startPrefixMapping(self, prefix, namespace):
  73.         pass
  74.  
  75.     def endPrefixMapping(self, prefix):
  76.         pass
  77.  
  78.     def startElementNS(self, name, qname, attrs):
  79.     
  80.         if name[0]!=TRIXNS:
  81.             self.error("Only elements in the TriX namespace are allowed.")
  82.  
  83.         if name[1]=="TriX":
  84.             if self.state==0:
  85.                 self.state=1
  86.             else:
  87.                 self.error("Unexpected TriX element")
  88.  
  89.         elif name[1]=="graph":
  90.             if self.state==1:
  91.                 self.state=2
  92.             else:
  93.                 self.error("Unexpected graph element")
  94.  
  95.         elif name[1]=="uri":
  96.             if self.state==2:
  97.                 # the context uri
  98.                 self.state=3
  99.             elif self.state==4:
  100.                 # part of a triple
  101.                 pass
  102.             else:
  103.                 self.error("Unexpected uri element")
  104.  
  105.         elif name[1]=="triple":
  106.             if self.state==2:
  107.                 # start of a triple
  108.                 self.triple=[]
  109.                 self.state=4
  110.             else:
  111.                 self.error("Unexpected triple element")
  112.  
  113.         elif name[1]=="typedLiteral":
  114.             if self.state==4:
  115.                 # part of triple
  116.                 self.lang=None
  117.                 self.datatype=None
  118.  
  119.                 try:
  120.                     self.lang=attrs.getValueByQName("lang")
  121.                 except:
  122.                     # language not required - ignore
  123.                     pass
  124.                 try: 
  125.                     self.datatype=attrs.getValueByQName("datatype")
  126.                 except KeyError:
  127.                     self.error("No required attribute 'datatype'")
  128.             else:
  129.                 self.error("Unexpected typedLiteral element")
  130.                 
  131.         elif name[1]=="plainLiteral":
  132.             if self.state==4:
  133.                 # part of triple
  134.                 self.lang=None
  135.                 self.datatype=None
  136.                 try:
  137.                     self.lang=attrs.getValueByQName("lang")
  138.                 except:
  139.                     # language not required - ignore
  140.                     pass
  141.  
  142.             else:
  143.                 self.error("Unexpected plainLiteral element")
  144.  
  145.         elif name[1]=="id":
  146.             if self.state==2:
  147.                 # the context uri
  148.                 self.state=3
  149.  
  150.             elif self.state==4:
  151.                 # part of triple
  152.                 pass
  153.             else:
  154.                 self.error("Unexpected id element")
  155.         
  156.         else:
  157.             self.error("Unknown element %s in TriX namespace"%name[1])
  158.  
  159.         self.chars=""
  160.  
  161.     
  162.     def endElementNS(self, name, qname):
  163.         if name[0]!=TRIXNS:
  164.             self.error("Only elements in the TriX namespace are allowed.")
  165.  
  166.         if name[1]=="uri":
  167.             if self.state==3:
  168.                 self.graph=Graph(store=self.store.store, identifier=URIRef(self.chars.strip()))
  169.                 self.state=2
  170.             elif self.state==4:
  171.                 self.triple+=[URIRef(self.chars.strip())]
  172.             else:
  173.                 self.error("Illegal internal self.state - This should never happen if the SAX parser ensures XML syntax correctness")
  174.  
  175.         if name[1]=="id":
  176.             if self.state==3:
  177.                 self.graph=Graph(self.store.store,identifier=self.get_bnode(self.chars.strip()))
  178.                 self.state=2
  179.             elif self.state==4:
  180.                 self.triple+=[self.get_bnode(self.chars.strip())]
  181.             else:
  182.                 self.error("Illegal internal self.state - This should never happen if the SAX parser ensures XML syntax correctness")
  183.  
  184.         if name[1]=="plainLiteral" or name[1]=="typedLiteral":
  185.             if self.state==4:
  186.                 self.triple+=[Literal(self.chars, lang=self.lang, datatype=self.datatype)]
  187.             else:
  188.                 self.error("This should never happen if the SAX parser ensures XML syntax correctness")
  189.  
  190.         if name[1]=="triple":
  191.             if self.state==4:
  192.                 if len(self.triple)!=3:
  193.                     self.error("Triple has wrong length, got %d elements: %s"%(len(self.triple),self.triple))
  194.  
  195.                 self.graph.add(self.triple)
  196.                 #self.store.store.add(self.triple,context=self.graph)
  197.                 #self.store.addN([self.triple+[self.graph]])
  198.                 self.state=2
  199.             else:
  200.                 self.error("This should never happen if the SAX parser ensures XML syntax correctness")
  201.  
  202.         if name[1]=="graph":
  203.             self.state=1
  204.  
  205.         if name[1]=="TriX":
  206.             self.state=0
  207.  
  208.  
  209.     def get_bnode(self,label):
  210.         if self.preserve_bnode_ids:
  211.             bn=BNode(label)
  212.         else:
  213.             if label in self.bnode:
  214.                 bn=self.bnode[label]
  215.             else: 
  216.                 bn=BNode(label)
  217.                 self.bnode[label]=bn
  218.         return bn
  219.                 
  220.  
  221.     def characters(self, content):
  222.         self.chars+=content
  223.  
  224.     
  225.     def ignorableWhitespace(self, content):
  226.         pass
  227.  
  228.     def processingInstruction(self, target, data):
  229.         pass
  230.  
  231.     
  232.     def error(self, message):
  233.         locator = self.locator
  234.         info = "%s:%s:%s: " % (locator.getSystemId(),
  235.                             locator.getLineNumber(), locator.getColumnNumber())
  236.         raise ParserError(info + message)
  237.